import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:exams_app/home_module/exams_module/view.dart';
import 'package:exams_app/net/DioManager.dart';
import 'package:exams_app/net/persisten_storage.dart';
import 'package:exams_app/widget/hexcolor.dart';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'logic.dart';
import 'dart:convert';

import 'package:common_utils/common_utils.dart';
class CodeLoginPage extends StatefulWidget {
  const CodeLoginPage({Key key}) : super(key: key);

  @override
  _CodeLoginPageState createState() => _CodeLoginPageState();
}

class _CodeLoginPageState extends State<CodeLoginPage> with SingleTickerProviderStateMixin {

  final LoginModuleLogic logic = Get.put(LoginModuleLogic());

  var _username = TextEditingController();

  var _pwd = TextEditingController();

  Timer _timer;

  int _countdownTime = 0;

  FocusNode _codeFocus = FocusNode();

  @override
  void initState() {
    super.initState();

  }

  void requestDataWithCodeLogin()async{

    BotToast.showLoading(clickClose: true);

    var prefs = await SharedPreferences.getInstance();

    var url = await prefs.get('urlStr');

    var params = {
      // 'name':'登录确认验证码',
      'mobile':_username.text,
      'type':'1',
      'verifyCode':_pwd.text
    };

    String result = await DioUtils(url: url).post('/api/v1/login/0',data:params);
    Map json = jsonDecode(result);

    Usesr _model = Usesr.fromJson(json);

    if (_model.errmsg == 'ok') {
      // await prefs.setString('acctoken', _model.data.accessToken);

      PersistentStorage().setStorage('acctoken', _model.data.accessToken);

      await prefs.setInt('uid', _model.data.uid);
      await prefs.setInt('partner_id', _model.data.partnerId);
      await prefs.setString('image128', _model.data.image128);
      await prefs.setString(
          'job_company_id', _model.data.jobCompanyId.toString());
      await prefs.setString('job_user_id', _model.data.jobUserId.toString());
      await prefs.setString('name', _model.data.name);
      await prefs.setString('companyIdName', _model.data.companyIdName);
      await prefs.setString('companyId', _model.data.companyId.toString());

      if(Get.isDialogOpen){
        Get.back();
      }
      BotToast.closeAllLoading();
      Get.off(HomeModulePage());


    } else {
      // Toast.toast(Get.overlayContext, msg: _model.message);
      // Get.back();
      BotToast.showText(text: _model.message);
      BotToast.closeAllLoading();
    }

  }

  void startCountdownTimer(){
    const oneSec = const Duration(seconds: 1);

    var callback = (timer) => {
      setState(() {
        if(_countdownTime<1){
          _timer.cancel();
        }else{
          _countdownTime = _countdownTime -1;
        }
      })
    };

    _timer = Timer.periodic(oneSec,callback);
  }




  @override
  void dispose() {

    super.dispose();

    if(_timer != null){
      _timer.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: ListView(
        children: [
          // Container(
          //   padding: EdgeInsets.only(top: 15),
          //   child: Text('DTCloud 销冠',style: Theme.of(context).textTheme.subtitle1,),
          // ),
          Center(
            child: Container(
                decoration: new BoxDecoration(
                  // color: Colors.white,
                  //设置四周圆角 角度
                  borderRadius: BorderRadius.all(Radius.circular(25.0)),
                  //设置四周边框
                  border: new Border.all(width: 1, color:HexColor('#DFDFDF')),
                ),
                margin: EdgeInsets.only(top: 20,left: 15,right: 15),
                child: Row(
                  mainAxisAlignment:MainAxisAlignment.spaceBetween,
                  children: [
                    Container(

                      margin: EdgeInsets.only(left: 25),
                      width: 200,
                      child: TextField(
                        controller: _username,
                        keyboardType: TextInputType.phone,
                        style: TextStyle(fontSize: 16,color: HexColor('#333333')),
                        decoration: InputDecoration(
                          hintText: '请输入手机号码',
                          hintStyle: TextStyle(fontSize: 16,color: HexColor('#BBBBBB')),
                          border: InputBorder.none,
                          // prefixIcon: Icon(Icons.phone_android,size: 15,),
                        ),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(right: 15),
                      width: 80,
                      child: GestureDetector(
                        child: Text(
                          _countdownTime > 0?'重新发送(${_countdownTime})':'获取验证码',
                          style: TextStyle(color:_countdownTime > 0
                              ? HexColor('#567BFD')
                              : HexColor(('#567BFD')),fontSize: 14,),
                        ),
                        onTap: (){

                          if(!RegexUtil.isMobileSimple(_username.text)) {

                            // Toast.toast(context,msg: '请输入正确的手机号码');
                            BotToast.showText(text: '请输入正确的手机号码');
                            return;
                          }
                          BotToast.showLoading(clickClose: true);

                          logic.requestDataSendCode(_username.text).then((json){
                            BotToast.showText(text: json['message']);

                            FocusScope.of(context).requestFocus(_codeFocus);     // 获取焦点


                            startCountdownTimer();
                            if(_countdownTime== 0){

                              setState(() {
                                _countdownTime = 59;
                              });

                            }
                          });



                        },
                      ),

                    )
                  ],
                )
            ),
          ),
          Center(
            child: Container(
              decoration: new BoxDecoration(
//背景
//                 color: Colors.white,
                //设置四周圆角 角度

                borderRadius: BorderRadius.all(Radius.circular(25.0)),
                //设置四周边框
                border: new Border.all(width: 1, color:HexColor('#DFDFDF')),


              ),

              margin: EdgeInsets.only(top: 10,right: 15,left: 15),
              child: Container(
                margin: EdgeInsets.only(left: 25),
                child: TextField(
                  focusNode: _codeFocus,
                  controller: _pwd,
                  style: TextStyle(fontSize: 16,color: HexColor('#333333')),
                  decoration: InputDecoration(
                    hintText: '请输入验证码',
                    hintStyle: TextStyle(fontSize: 16,color: HexColor('#BBBBBB')),
                    border: InputBorder.none,
                    // prefixIcon: Image.asset(A.assets_pwd),
                  ),
                ),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 72,right: 15,left: 15),
            width: Get.width,
            height: 45,
            child: RaisedButton(
              elevation: 0,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(22),
              ),
              color:Theme.of(context).primaryColor,
              onPressed: ()async{
                var prefs = await SharedPreferences.getInstance();

                if(prefs.getString('urlStr')==null){
                  // Toast.toast(context,msg: '请先设置BaseUrl');
                  BotToast.showText(text: '请先设置BaseUrl');
                  return;
                }
                if(_username.text.length == 0){
                  // Toast.toast(context,msg: '请输入手机号码');
                  BotToast.showText(text: '请输入手机号码');
                  return;
                }
                if(!RegexUtil.isMobileSimple(_username.text)){
                  BotToast.showText(text: '请输入正确的手机号码');
                  return;
                }

                // requestDataLogin();

                requestDataWithCodeLogin();

              },
              child: Text('登录',style: TextStyle(color: Colors.white),),
            ),
          ),
         // GestureDetector(
         //   onTap: (){
         //     // Get.to(RegisterPage());
         //   },
         //   child:  Container(
         //     padding: EdgeInsets.only(right: 25,top: 15),
         //     alignment: Alignment.centerRight,
         //     child: Text('我要注册',style: TextStyle(fontSize: 14,color: Theme.of(context).primaryColor),),
         //     width: Get.width,
         //     // color: Colors.red,
         //   ),
         // )

        ],
      ),
    );
  }


}


